package cn.ibobo.lease.app.service.impl;

import cn.ibobo.lease.app.dao.DictMapper;
import cn.ibobo.lease.app.dao.UserMapper;
import cn.ibobo.lease.app.service.UserCouponService;
import cn.ibobo.lease.app.service.UserPointService;
import cn.ibobo.lease.common.base.BaseMapper;
import cn.ibobo.lease.common.base.BaseServiceImpl;
import cn.ibobo.lease.app.dao.UserBalanceMapper;
import cn.ibobo.lease.common.dto.*;
import cn.ibobo.lease.app.service.UserBalanceService;
import cn.ibobo.lease.common.enums.ResultEnum;
import cn.ibobo.lease.common.util.DateUtil;
import cn.ibobo.lease.common.util.UuidUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;


/**
 * 用户点金记录表业务处理接口
 * @Author lililiang
 * @Date 2019-02-16 18:41:19
 */
@Service
public class UserBalanceServiceImpl extends BaseServiceImpl<UserBalanceDTO, String> implements UserBalanceService {

    private static final Log LOGGER = LogFactory.getLog(UserBalanceServiceImpl.class);

    @Autowired
    private UserBalanceMapper mapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserBalanceMapper userBalanceMapper;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private UserPointService userPointService;

    @Override
    protected BaseMapper<UserBalanceDTO, String> getMapper() {
        return mapper;
    }

    /**
     * 用户点金记录表列表
     * @Author lililiang
     * @Date 2019-02-16 18:41:19
     * @Param
     * @Return
     */
    @Override
    public List<UserBalanceDTO> list4Page(UserBalanceDTO entity, Integer pageNum, Integer... pageSize) {
        return super.list4Page(entity, pageNum, pageSize);
    }

    /**
     * 用户点金记录表列表（无分页）
     * @Author lililiang
     * @Date 2019-02-16 18:41:19
     * @Param
     * @Return
     */
    @Override
    public List<UserBalanceDTO> listByCondition(UserBalanceDTO entity) {
        return super.listByCondition(entity);
    }

    /**
     * 查询用户点金记录表详情信息
     * @Author lililiang
     * @Date 2019-02-16 18:41:19
     * @Param
     * @Return
     */
    @Override
    public UserBalanceDTO queryOneByPk(String id) {
        return super.queryOneByPk(id);
    }

    /**
     * 保存用户点金记录表信息
     * @Author lililiang
     * @Date 2019-02-16 18:41:19
     * @Param
     * @Return
     */
    @Override
    @Transactional
    public Integer save(UserBalanceDTO entity) {
        return super.save(entity);
    }

    /**
     * 删除用户点金记录表信息
     * @Author lililiang
     * @Date 2019-02-16 18:41:19
     * @Param
     * @Return
     */
    @Override
    @Transactional
    public Integer delete(String id) {
        return super.delete(id);
    }

    /**
     * @Description 用户充值回调业务
     * @Author lililiang
     * @Date 2019/2/16 19:03
     * @Param [attachMap]
     * @Return java.lang.Integer
     */
    @Override
    @Transactional
    public Integer balance(HashMap attachMap){
        //1. 用户账户增加充值金额
        UserDTO user = new UserDTO();
        user.setUid(attachMap.get("uid").toString());
        user.setType((byte)1);//1增加  2减少
        user.setBalance(new BigDecimal(attachMap.get("balance").toString()));
        if(userMapper.balance(user) <= 0){
            return  ResultEnum.FAIL.getCode();
        }
        //2. 增加充值记录
        UserBalanceDTO userBalanceDTO = new UserBalanceDTO();
        userBalanceDTO.setId(UuidUtil.getUuid());
        userBalanceDTO.setUid(attachMap.get("uid").toString());
        userBalanceDTO.setMoney(new BigDecimal(attachMap.get("balance").toString()));
        userBalanceDTO.setStatus(0);
        userBalanceDTO.setCreatetm(DateUtil.getNow());
        userBalanceDTO.setWxOrderId(attachMap.get("wxOrderId").toString());
        userBalanceDTO.setType(attachMap.get("type").toString());
        if(userBalanceMapper.add(userBalanceDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return  ResultEnum.FAIL.getCode();
        }

        //4. 根据消费返还点金券比例计算返还的点金券金额
        DictDTO dict = new DictDTO();
        dict.setMasterCode("coupon_ratio");
        List<DictDTO> dictDTOS = dictMapper.listByCondition(dict);
        if(dictDTOS == null || dictDTOS.size() == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        //5. 生成点金券赠送记录   修改会员点金总额
        UserCouponDTO couponDTO = new UserCouponDTO();
        couponDTO.setUid(attachMap.get("uid").toString());
        couponDTO.setMoney(new BigDecimal(attachMap.get("balance").toString())
                .multiply(new BigDecimal(dictDTOS.get(0).getRemark().toString()))
                .multiply(new BigDecimal("0.01")));//查询的比例为百分比，需要乘0.01
        couponDTO.setType(2); //1平台发放，2充值赠送，3租赁赠送，4线上购物赠送，5线下购物赠送 6线下购物使用
        couponDTO.setBusId(userBalanceDTO.getId());
        if(userCouponService.coupon(couponDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        //6. 根据消费返还积分比例计算返还的积分数量
        dict.setMasterCode("point_ratio");
        dictDTOS = dictMapper.listByCondition(dict);
        if(dictDTOS == null || dictDTOS.size() == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        //7. 生成积分赠送记录 / 修改会员当前积分/总积分
        UserPointDTO pointDTO = new UserPointDTO();
        pointDTO.setUid(attachMap.get("uid").toString());
        pointDTO.setPoint(new BigDecimal(attachMap.get("balance").toString())
                .multiply(new BigDecimal(dictDTOS.get(0).getRemark().toString())
                        .multiply(new BigDecimal("0.01")))
                .intValue());
        pointDTO.setType((byte)2);//1 使用积分  2 充值赠送  3 租赁赠送  4线上购物赠送
        pointDTO.setBusId(userBalanceDTO.getId());
        if (userPointService.point(pointDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        return ResultEnum.SUCCESS.getCode();
    }
}
